package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.TreeNode;

/**
 * 从中序与后续遍历序列构造二叉树
 * https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
 *
 * @time 2024/1/9
 */
public class BuildTreeFromInPost {

//    public static void main(String[] args) {
//        BuildTreeFromInPost bt = new BuildTreeFromInPost();
//        int[] post = {9, 15, 7, 20, 3};
//        int[] in = {9, 3, 15, 20, 7};
//        TreeNode root = bt.buildTree(in, post);
//    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return search(postorder, inorder, 0, postorder.length - 1, 0, inorder.length - 1);
    }

    private TreeNode search(int[] post, int[] in, int postLeft, int postRight, int inLeft, int inRight) {
        if (postLeft > postRight || inLeft > inRight) {
            return null;
        }
        TreeNode root = new TreeNode(post[postRight]);
        if (postLeft == postRight) {
            return root;
        }

        for (int i = inLeft; i <= inRight; i++) {
            if (in[i] == post[postRight]) {
                if (i - inLeft > 0) {
                    root.left = search(post, in, postLeft, postLeft + i - inLeft - 1, inLeft, i - 1);
                }

                int tmp = inRight - i;
                if (tmp > 0) {
                    root.right = search(post, in, postLeft + i - inLeft, postRight - 1, i + 1, inRight);
                }
                break;
            }
        }
        return root;
    }
}
